import { useEffect } from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { GlobalContext } from './config'
import { Provider } from 'react-redux';
import { store } from './store'

import { appLocalStorage, checkLogin } from './utils/tools'
import { useAppDispatch } from './utils/hooks'
import { appConfigActions } from './store/appConfigSlice'
import { getCurrentUserInfoApi } from './services'
import { userActions } from './store/userSlice'
import { offActions } from './store/offSlice'
import App from './app'

/**
 * styte  样式
 */
import './style/tailwindcss/index.css'
import './style/index.less'
import 'magic-ui-react/style'
import 'magic-ui-react/icons/css'
import 'magic-ui-react/theme'
// import 'magic-ui-react/globalLess'

window.matchMedia("prefers-color-scheme").onchange = (themeMedia) => {
  console.log('themeMedia', themeMedia);
}

document.onmouseup = () => {
  document.onmouseleave = null
}

const Main = () => {

  const dispatch = useAppDispatch()

  /**
   * 获取用户信息
   */
  const getUserInfo = async () => {
    try {
      const userInfoRes = await getCurrentUserInfoApi()
      const {
        appConfig,
        ...userInfo
      } = userInfoRes.data

      dispatch(userActions.updateUserInfo(userInfo))
    } catch (error) {
    }
  }

  /**
   * 网站点击事件初始化
   */
  const documentClickInit = () => {
    document.addEventListener('click', () => {
      dispatch(offActions.update({
        edit: false
      }))
    })
  }

  const appInit = async () => {
    // 阻止右键默认事件
    document.oncontextmenu = (e) => {
      e.preventDefault()
    }

    documentClickInit()

    if (checkLogin()) {
      getUserInfo()
    }

    const appConfig = appLocalStorage.getValue('appConfig')
    dispatch(appConfigActions.initAppConfig(appConfig || {}))

    if (!appLocalStorage.getValue('lang')) {
      appLocalStorage.setValue('lang', 'zh-CN')
    }
  }

  useEffect(() => {
    appInit()
  }, [])

  return (
    <>
      <App />
    </>
  )
}

ReactDOM
  .createRoot(document.getElementById('root') as HTMLElement)
  .render(
    // <React.StrictMode>
    <Provider store={store}>
      <GlobalContext.Provider
        value={{
          lang: 'zh-CN',
          theme: 'light'
        }}
      >
        <BrowserRouter>
          <Main />
        </BrowserRouter>
      </GlobalContext.Provider>
    </Provider>
    // </React.StrictMode >
  )
